<template>
  <div class="app-container">
    <el-form  :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医院编码" prop="hospitalCode">
        <el-input
          v-model="queryParams.hospitalCode"
          placeholder="医院编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表单名称" prop="formTitle">
        <el-input
          v-model="queryParams.formTitle"
          placeholder="请输入表单名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
         <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:formsetting:add']"
        >新增表单</el-button>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    
    <el-table v-loading="loading" :data="formsettingList" @selection-change="handleSelectionChange">
      <el-table-column label="表单配置id" align="center" prop="formSettingId" />
      <el-table-column label="医院编码" align="center" prop="hospitalCode" />
      <el-table-column label="表单名称" align="center" prop="formTitle" />
      <el-table-column label="短名称" align="center" prop="formShortName" />
      <el-table-column label="一级标题" align="center" prop="firstTitle" />
      <el-table-column label="二级标题" align="center" prop="secondTitle" />
      <el-table-column label="状态" align="center" prop="status">
         
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            @change="updateFormStatus(scope.row)"
            :inactive-value="1"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row,1)" v-hasPermi="['manage:formsetting:edit']">修改</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row,2)">表单小项</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:formsetting:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改表单配置对话框 -->
    <el-dialog :title="title" v-model="open" width="1100px" append-to-body>
      <el-form ref="formsettingRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-show="iseditsmall==1" label="医院编码" prop="hospitalCode">
          <el-input v-model="form.hospitalCode" placeholder="医院编码" />
        </el-form-item>
        <el-form-item v-show="iseditsmall==1" label="表单名称" prop="formTitle">
          <el-input v-model="form.formTitle" placeholder="请输入表单名称" />
        </el-form-item>
        <el-form-item v-show="iseditsmall==1" label="短名称" prop="formShortName">
          <el-input v-model="form.formShortName" placeholder="请输入短名称" />
        </el-form-item>
        <el-form-item v-show="iseditsmall==1" label="一级标题" prop="firstTitle">
          <el-input v-model="form.firstTitle" placeholder="请输入一级标题" />
        </el-form-item>
        <el-form-item v-show="iseditsmall==1" label="二级标题" prop="secondTitle">
          <el-input v-model="form.secondTitle" placeholder="请输入二级标题" />
        </el-form-item>
        <el-divider v-show="iseditsmall==1" content-position="center">单据大项信息</el-divider>
        <el-row justify="end" style="margin-bottom:8px">
          <el-button size="mini" type="primary" icon="Plus" @click="handleAddFormSettingBig">添加大项</el-button>
        </el-row>
        <el-table atyle="width:100%" :data="formSettingBigList" :row-class-name="rowFormSettingBigIndex" @selection-change="handleFormSettingBigSelectionChange" ref="formSettingBig">
          <el-table-column label="表单大项名称" prop="name">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入名称" />
            </template>
          </el-table-column>
          <el-table-column label="序号" prop="sort" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.sort" placeholder="请输入序号" />
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态">
                <el-option label="启用" :value="0" />
                <el-option label="禁用" :value="1" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120px">
            <template #default="scope">
              <el-button v-show="iseditsmall!=1" link type="primary" icon="Edit" @click="editsmall(scope.row)">小项管理</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDeleteBigItem(scope.row)" v-hasPermi="['manage:formsetting:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>





    <!-- 添加或修改表单配置对话框 -->
    <el-dialog :title="pageSmallItem.name+'小项配置'" v-model="pageSmallItemDialog" width="95%" append-to-body>
      <el-form ref="formsettingRef" :model="form" :rules="rules" label-width="80px">
        <el-row justify="end" style="margin-bottom:8px">
          <el-button size="mini" type="primary" icon="Plus" @click="handleAddFormSettingSmall">添加小项</el-button>
        </el-row>
        <el-divider v-show="iseditsmall==1" content-position="center">{{ pageSmallItem.name }}</el-divider>
        <el-table size="small" atyle="width:100%" :data="formSettingSmallList" :row-class-name="rowFormSettingBigIndex"  ref="formSettingBig">
          <el-table-column label="表单小项名称" prop="name">
            <template #default="scope">
              <el-input v-model="scope.row.label" placeholder="请输入名称" />
            </template>
          </el-table-column>
          <el-table-column label="序号" prop="sort" width="60">
            <template #default="scope">
              <el-input v-model="scope.row.sort" placeholder="" />
            </template>
          </el-table-column>
           <el-table-column label="组件类型" prop="component" width="130">
            <template #default="scope">
              <el-select v-model="scope.row.component" placeholder="">
                <el-option
                  v-for="dict in form_component"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
             
            </template>
          </el-table-column>
        
           <el-table-column label="单位" prop="unit" width="70">
            <template #default="scope">
              <el-input v-model="scope.row.unit" placeholder="" />
            </template>
          </el-table-column>
           <el-table-column label="默认文本" prop="defaultText">
            <template #default="scope">
              <el-input v-model="scope.row.defaultText" placeholder="默认文本" />
            </template>
          </el-table-column>
            <el-table-column label="默认选" prop="sort" width="60" align="center">
            <template #default="scope">
              <el-checkbox v-model="scope.row.isSelect" label="" size="large" />
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态">
                <el-option label="启用" :value="0" />
                <el-option label="禁用" :value="1" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="60">
            <template #default="scope">
            
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:formsetting:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormSmall">确 定</el-button>
          <el-button @click="pageSmallItemDialog=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Formsetting">
import { listFormsetting, getFormsetting, delFormsetting, addFormsetting, updateFormsetting } from "@/api/manage/formsetting";
import { delFormsettingbig } from "@/api/manage/formsettingbig";
import { addFormsettingsmall,listFormsettingsmall } from "@/api/manage/formsettingsmall";


const { proxy } = getCurrentInstance();
const { form_component } = proxy.useDict('form_component');
const formsettingList = ref([]);
const formSettingBigList = ref([]);
const formSettingSmallList=ref([])
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedFormSettingBig = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
let iseditsmall=ref(1)
let pageSmallItemDialog=ref(false)
let pageSmallItem=ref({})
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    hospitalCode: null,
    formTitle: null,
    formShortName: null,
    firstTitle: null,
    secondTitle: null,
    status: null,
  },
  rules: {
    formSettingId: [
      { required: true, message: "表单配置id不能为空", trigger: "blur" }
    ],
    hospitalCode: [
      { required: true, message: "医院编码不能为空", trigger: "blur" }
    ],
    formTitle: [
      { required: true, message: "表单名称不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    createBy: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ],
    updateBy: [
      { required: true, message: "更新人不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询表单配置列表 */
function getList() {
  loading.value = true;
  listFormsetting(queryParams.value).then(response => {
    formsettingList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    formSettingId: null,
    hospitalCode: null,
    formTitle: null,
    formShortName: null,
    firstTitle: null,
    secondTitle: null,
    status: null,
    delFlag: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null
  };
  formSettingBigList.value = [];
  proxy.resetForm("formsettingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.formSettingId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加表单配置";
}

/** 修改按钮操作 */
function handleUpdate(row,editsmall) {
  pageSmallItem.value=row
  iseditsmall.value=editsmall
  reset();
  const _formSettingId = row.formSettingId || ids.value
  getFormsetting(_formSettingId).then(response => {
    form.value = response.data;
    formSettingBigList.value = response.data.formSettingBigList;
    open.value = true;
    title.value = "修改表单配置";
  });
}

function editsmall(row){

  pageSmallItemDialog.value=true
  pageSmallItem.value=row

  listFormsettingsmall({
    "formSettingBigId": pageSmallItem.value.formSettingBigId
  }).then(response => {
   formSettingSmallList.value=response.rows.map(item=>{
    item.isSelect=item.isSelect==1?false:true
    return item
   })
  });
 
}

function submitFormSmall(){
    let transData=JSON.parse(JSON.stringify(formSettingSmallList.value))
    transData=transData.map(item=>{
      item.isSelect=item.isSelect?0:1
      return item
    })
    addFormsettingsmall(transData).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      pageSmallItemDialog.value=false
      //getList();
    });
}

/*****更新表单状态******/

function updateFormStatus(row){
  delete row.formSettingBigList;
  updateFormsetting(row).then(response => {
    proxy.$modal.msgSuccess("修改成功");
    open.value = false;
    getList();
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formsettingRef"].validate(valid => {
    if (valid) {
      form.value.formSettingBigList = formSettingBigList.value;
      if (form.value.formSettingId != null) {
        updateFormsetting(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFormsetting(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/***删除大项条目****/

function handleDeleteBigItem(row){
  const _formSettingIds = row.formSettingBigId;
  proxy.$modal.confirm('是否确认删除表单配置编号为"' + _formSettingIds + '"的数据项？').then(function() {
    return delFormsettingbig(_formSettingIds);
  }).then(() => {
    handleUpdate(pageSmallItem.value,1);
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _formSettingIds = row.formSettingId || ids.value;
  proxy.$modal.confirm('是否确认删除表单配置编号为"' + _formSettingIds + '"的数据项？').then(function() {
    return delFormsetting(_formSettingIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 清单大项序号 */
function rowFormSettingBigIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/*********新增小项********/

function handleAddFormSettingSmall(){
  let obj = {};
  obj.label = "";
  obj.sort = formSettingSmallList.value.length+1;
  obj.component = "";
  obj.unit = "";
  obj.isSelect = "";
  obj.defaultText = "";
  obj.valueMin = "";
  obj.valueMax = "";
  obj.labelRemark = "";
  obj.formSettingBigId=pageSmallItem.value.formSettingBigId
  formSettingSmallList.value.push(obj);
}

/** 清单大项添加按钮操作 */
function handleAddFormSettingBig() {
  let obj = {};
  obj.name = "";
  obj.sort = formSettingBigList.value.length+1;
  obj.status = "";
  formSettingBigList.value.push(obj);
}

/** 清单大项删除按钮操作 */
function handleDeleteFormSettingBig() {
  if (checkedFormSettingBig.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的清单大项数据");
  } else {
    const formSettingBigs = formSettingBigList.value;
    const checkedFormSettingBigs = checkedFormSettingBig.value;
    formSettingBigList.value = formSettingBigs.filter(function(item) {
      return checkedFormSettingBigs.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleFormSettingBigSelectionChange(selection) {
  checkedFormSettingBig.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/formsetting/export', {
    ...queryParams.value
  }, `formsetting_${new Date().getTime()}.xlsx`)
}

getList();
</script>
